package models

import (
	"SSO/tools"
	"fmt"
)

type User struct {
	Id       int    `json:"id"`
	Username string `json:"username"`
	Password string `json:"password"`
}

type Users struct{}


func (this Users) CheckUsername(username string) (err error){
	if username == "" {
		return fmt.Errorf("用户名为空")
	}
	return nil
}

func (this Users) CheckPassword(password string) (err error){
	if password == "" {
		return fmt.Errorf("密码不能为空")
	}
	return nil
}

func (this Users) GetByUsernameAndPassword(username, password string) (*User, error) {
	users := make([]User, 0)
	r := tools.GetMysqlDB().Where("username = ?", username).Where("password = ?", password).Find(&users)
	if r.Error != nil {
		return nil, r.Error
	}

	if len(users) == 0 {
		return nil, nil
	}

	return &users[0], nil
}

func (Users) GetByUsername(username string) (*User, error) {
	users := make([]User, 0)
	r := tools.GetMysqlDB().Where("username = ?", username).Find(&users)
	if r.Error != nil {
		return nil, r.Error
	}

	if len(users) == 0 {
		return nil, nil
	}
	return &users[0], nil
}

func (Users) GetById(id int) (*User, error) {
	users := make([]User, 0)
	r := tools.GetMysqlDB().Where("id = ?", id).Find(&users)
	if r.Error != nil {
		return nil, r.Error
	}
	if len(users) == 0 {
		return nil, nil
	}
	return &users[0], nil
}

func (Users) Create(username, password string) (id int, err error) {

	passwordMd5 := tools.Function{}.GetStrMd5(password)
	user := User{
		Username: username,
		Password: passwordMd5,
	}
	r := tools.GetMysqlDB().Create(&user)
	if r.Error != nil {
		return -1, r.Error
	}
	return user.Id, nil
}

func (this Users) Delete(username string) (err error) {
	user, err :=  this.GetByUsername(username)
	if err != nil {
		return err
	}
	if user == nil {
		return fmt.Errorf("用户不存在")
	}

	r := tools.GetMysqlDB().Delete(&user)
	if r.Error != nil {
		return r.Error
	}
	return nil

}

func (this Users) UpdatePassword(username, newPassword string) (err error) {
	user, err := this.GetByUsername(username)
	if err != nil {
		return
	}
	if user == nil {
		return fmt.Errorf("用户[%s]不存在", username)
	}

	str := tools.Function{}.GetStrMd5(newPassword)
	user.Password = str
	r := tools.GetMysqlDB().Save(&user)

	if r.Error != nil {
		err = r.Error
	}
	return
}

